<template lang="">
    <div>
     <div class="search_header">
          <van-icon name="arrow-left" class="back_icon" color="#fff" @click="$router.go(-1)"/>
        <div class="search_input" v-focus>
            <van-search
            v-model="searchkeyword"
            shape="round"
            background="#007bff"
            placeholder="请输入搜索关键词"
            @input="inputFn()"
            @search="onSearch"
          />
        </div>
      </div>
      <div class="ass_menu"  v-if="searchkeyword.length!==0">
         <ul>
          <li v-for="(assItem,index) in assMetu" :key="index" @click="assItemFn(assItem)">
            <van-icon name="search" size="0.5266666666666667rem" /><span class="ass_content" v-html="makeStr(assItem,searchkeyword)"></span>
          </li>
         </ul>
      </div>
        <div class="history_search" v-else>
        <div class="history_cell">
          <van-cell title="搜索历史">
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #right-icon>
             <van-icon name="failure" size="0.5266666666666667rem" @click="clearHistory"/>
            </template>
          </van-cell>
        </div>
        <div class="history_list">
         <span class="history_item" v-for="(item,index) in historylist" :key="index" @click="historyItemFn(item)">{{item}}</span>
        </div>
      </div>
    </div>
</template>
<script>
export default {
  name: 'SearchC',
  data () {
    return {
      searchkeyword: '',
      // 定时器
      timer: null,
      assMetu: [],
      historylist: JSON.parse(localStorage.getItem('HISTORY')) || []
    }
  },
  // mounted () {
  //   this.$bus.$emit('getKw', this.searchkeyword)
  // },
  methods: {
    // 防抖操作
    inputFn () {
      // 清除定时器
      clearInterval(this.timer)
      this.timer = null
      // 开启定时器
      if (this.searchkeyword.length === 0) {
        console.log('clear')
        this.assMetu = []
      } else {
        this.timer = setTimeout(async () => {
          const res = await this.$API.reqASSMetu(this.searchkeyword.trim())
          console.log(res)
          if (res.status === 200) {
            if (res.data.data.options[0] !== null) {
              if (this.timer !== null) {
                console.log('enter')
                this.assMetu = res.data.data.options
              }
            } else {
              this.assMetu = []
            }
          }
        }, 100)
      }
    },
    // 关键字的高亮的实现
    // 考虑的问题：1.替换，要使用v-html是用html模板，是字体颜色变成红色
    // 2.使用replce方法，因为替换的文字要是本来的文字内容（有的大写，有的小写），并且正则表示式要用变量，然后忽略大小写
    makeStr (orginalStr, target) {
      // 匹配模式为忽略大小写和全局匹配
      const reg = new RegExp(target, 'ig')
      return orginalStr.replaceAll(reg, (match) => {
        console.log(match)
        return `<span style="color:red">${match}</span>`
      })
    },
    enterSearchResult (str) {
      this.historylist.push(str)
      this.makeList()
      // 也加入回调，这样在跳转前能够将历史记录存入本地
      setTimeout(() => {
        // params参数，两种方式的跳转
        // this.$router.push({ name: 'searchResult', params: { kw: this.searchkeyword } })
        this.$router.push(`/search/${str}`)
      }, 100)
    },
    // 搜索框
    onSearch () {
      if (this.searchkeyword.length !== 0) {
        this.enterSearchResult(this.searchkeyword)
      }
    },
    // 联想菜单
    assItemFn (str) {
      this.enterSearchResult(str)
    },
    historyItemFn (str) {
      this.enterSearchResult(str)
      console.log(str)
    },
    // 清除搜索记录
    clearHistory () {
      this.historylist = []
      localStorage.removeItem('HISTORY')
    },
    makeList () {
      this.historylist = Array.from(new Set(this.historylist))
    }
  },
  // 异步操作
  watch: {
    historylist: {
      deep: true,
      handler () {
        // 将搜索记录存入本地
        // 去重
        // const his = Array.from(new Set(this.historylist))
        localStorage.setItem('HISTORY', JSON.stringify(this.historylist))
      }
    }
  }
}
</script>
<style lang="less" scoped>
.search_header{
display: flex;
width:100vw;
background-color: #007bff;
.back_icon{
margin: auto 0;
margin-left:10px;
}
.search_input
{
margin-left: 10px;
width: 90vw;
}
}
.ass_menu{
  margin-top:10px;
ul{
  li{
   height: 30px;
   font-size: 16px;
   margin-top:15px;
   border-bottom: 1px solid #ccc;
 /deep/ .van-icon{
   padding-left:10px;
   }
   .ass_content{
     padding-left:30px;
   }
  }
}
}
.history_list
{
  margin: 0 15px;
 .history_item
 {
  display: inline-block;
  height: 35px;
  padding: 0 3px;
  margin-right: 8px;
  margin-bottom: 10px;
  line-height: 35px;
  background-color:rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-size: 16px;
 }
}
</style>
